<template>
  <a-card title="更多搭配">
    <a-tabs @change="tabChange" :activeKey="type">
      <a-tab-pane :key="item.type" :tab="item.name" v-for="item in tabs"></a-tab-pane>
    </a-tabs>
    <!-- <a-row :gutter="48">
        <a-col :xxl="6" :xl="6" :lg="12" :sm="24"> -->
    <div class="table-page-search-wrapper">
      <a-row :gutter="20">
        <a-form layout="inline" :form="form" @submit="handleSubmit">
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">

            <a-form-item label="商品款号">
              <a-input placeholder="输入商品款号搜索" v-decorator="['productNoMore']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="品牌">
              <a-select placeholder="全部" v-decorator="['brandId']">
                <a-select-option :value="item.weid" v-for="item in brands"
                  :key="item.weid">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="年份">
              <a-date-picker format="YYYY" :open="openYear" @openChange="openChange" @change="handleChange" mode="year"
                @panelChange="panelChange" :value="year" />
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="季节">
              <a-select placeholder="全部" v-decorator="['season']">
                <a-select-option :value="item" v-for="(item, index) in seasons" :key="item.id">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="波段(月)">
              <a-select placeholder="全部" v-decorator="['bandMonth']">
                <a-select-option :value="item" v-for="(item, index) in months" :key="`m-${item}`">
                  {{ `${item}月` }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="波段">
              <a-select placeholder="全部" v-decorator="['bands']">
                <a-select-option :value="item" v-for="(item, index) in ['A', 'B', 'C']" :key="`m-${item}`">
                  {{ `${item}` }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="搭配风格">
              <a-select placeholder="全部" v-decorator="['label']">
                <a-select-option :value="item.code" v-for="item in styleOptions" :key="item.code">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="来源">
              <a-select placeholder="全部" v-decorator="['source']">
                <a-select-option :value="item.code" v-for="item in typeList" :key="item.code">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="搭配类型">
              <a-select placeholder="全部" v-decorator="['sonType']">
                <a-select-option :value="item.code" v-for="(item, index) in lookTypes" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
            <a-form-item label="创建时间">
              <a-range-picker format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']" v-decorator="['time']" />
            </a-form-item>
          </a-col>
          <a-col :xxl="12" :xl="12" :lg="24" :sm="24">
            <a-form-item>
              <a-button type="primary" html-type="submit">搜索</a-button>
              <a-button type="primary" @click="resetForm" style="margin-left: 10px">重置</a-button>
              <a-button type="primary" @click="$router.push(`/micromall/marketing/collocation/more/create`)"
                style="margin-left: 10px">新建</a-button>
            </a-form-item>
          </a-col>
        </a-form>

      </a-row>
      <div style="padding:10px" v-if="type != 1">
        <a-button type="primary" v-if="type == 2" :disabled="!hasSelected" style="margin-right:10px"
          @click="batch('prohibit')">批量禁用</a-button>
        <a-button type="primary" v-if="type == 3" :disabled="!hasSelected" style="margin-right:10px"
          @click="batch('open')">批量启用</a-button>
        <a-button type="primary" :disabled="!hasSelected" @click="batch('del')">批量删除</a-button>
      </div>
    </div>
    <a-table bordered :columns="columns" :rowKey="record => record.id"
      :row-selection="type == 1 ? null : { selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :data-source="dataSource" :pagination="pagination" :scroll="{ x: true }" @change="handleTableChange"
      :loading="loading">
      <template slot="mainPicture" slot-scope="text, record">
        <img @click="prevHandle(record.figure)"
          :src="!record.figure ? 'https://picttype1.jnby.com/collocation/image-empty.png' : record.figure" alt=""
          style="width: 50px; height: 50px" />
        <!-- <span v-else>/</span> -->
      </template>
      <template slot="collocationParagraph" slot-scope="text, record">
        <GoodsImgList :collocationGoods="record.collocationProductList" />
      </template>
      <span slot="labelName" slot-scope="text, record">{{ filterLable(record.labelNameId) }}</span>
      <template slot="actions" slot-scope="text, record">
        <a-button type="link" @click="handleEdit(record)" v-if="type != 1">编辑</a-button>
        <a-button type="link" v-if="type == 1" @click="handleEdit(record, 1)">完善</a-button>
        <a-button type="link" @click="deleteCollcation(record.id)">删除</a-button>
        <a-button type="link" @click="updateStatus(record.id, 3)" v-if="type == 2">禁用</a-button>
        <a-button type="link" @click="updateStatus(record.id, 2)" v-if="type == 3">启用</a-button>
      </template>
    </a-table>
    <PreviewImg :showPreviewImg.sync="showPreviewImg" :url="previewUrl"></PreviewImg>
  </a-card>
</template>
<script>
import { listMixin } from '../../util/listMixin'
import GoodsImgList from '../../components/GoodsImgList.vue'
import PreviewImg from '../../components/PreviewImg.vue'
import { listMore, getStyle, updateMoreCollocationStatus, removeMoreCollocation, moreHandleNum, batchUpdateMore, batchDeleteMore, lookLabel, lookType } from '@api/micromall/collocation.js'
import { batch } from '../util'
import collocationMixin from '../collocationMixin'

const columns = [
  {
    title: '搭配图',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'mainPicture' }
  },
  {
    title: '搭配款',
    width: 200,
    scopedSlots: { customRender: 'collocationParagraph' }
  },
  {
    title: '搭配风格',
    width: 200,
    scopedSlots: { customRender: 'labelName' }
  },
  {
    title: '来源',
    width: 200,
    dataIndex: 'source'
  },
  {
    title: '创建时间',
    width: 200,
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    width: 200,
    scopedSlots: { customRender: 'actions' }
  }
]
const columns2 = [

  {
    title: '搭配款',
    width: 200,
    scopedSlots: { customRender: 'collocationParagraph' }
  },
  {
    title: '来源',
    width: 200,
    dataIndex: 'source'
  },
  {
    title: '创建时间',
    width: 200,
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    width: 200,
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  mixins: [collocationMixin],
  components: {
    GoodsImgList,
    PreviewImg
  },
  data() {
    return {
      type: 2,
      perfectNum: 0,
      tabs: [
        {
          name: '已启用',
          type: 2
        },
        {
          name: '待完善',
          type: 1
        },
        {
          name: '已禁用',
          type: 3
        }
      ],
      sonTypeList: [
        {
          name: '搭配师',
          code: 1001
        },
        {
          name: '明星导购',
          code: 3001
        },
        {
          name: '普通导购',
          code: 3002
        },
        {
          name: 'KOU导购',
          code: 3003
        },
        {
          name: '总部经理',
          code: 3004
        },
        {
          name: '大区经理',
          code: 3005
        },
        {
          name: 'BOX+主动要盒素材',
          code: 2001
        },
        {
          name: 'JNBY陈列',
          code: 2002
        },
        {
          name: '抖音同款',
          code: 2003
        },
        {
          name: '品牌代言人',
          code: 2004
        },
        {
          name: '主题穿搭推荐',
          code: 2005
        },
        {
          name: '小红书达人同款',
          code: 2006
        },
        {
          name: '营销活动',
          code: 2007
        },
        {
          name: '明星达人穿搭',
          code: 2008
        },
        {
          name: '搭配图&单品图',
          code: 2009
        },
        {
          name: '新品季度大片',
          code: 2010
        },
        {
          name: '社群素材',
          code: 2011
        },
        {
          name: 'JNBYHOME-O',
          code: 2012
        },
        {
          name: 'JNBYHOME-M',
          code: 2013
        },
        {
          name: 'JNBYHOME-H',
          code: 2014
        },
        {
          name: 'JNBYHOME-E',
          code: 2015
        },
        {
          name: '总部搭配师',
          code: 2016
        },
        {
          name: '会员部',
          code: 2017
        },
        {
          name: '品牌代言人同款',
          code: 2018
        }
      ],
      lookTypes: [],
      // typeList: [
      //   {
      //     name: '有搭素材',
      //     code: 'B10-A01'
      //   },
      //   {
      //     name: '零售素材',
      //     code: '零售素材'
      //   },
      //   {
      //     name: '导购素材',
      //     code: '导购素材'
      //   },
      //   {
      //     name: '微商城',
      //     code: '微商城'
      //   }
      // ],
      url: {
        list: ''
      },
      columns,
      dataSource: [],
      visible: false,
      styleOptions: [],
      loading: false,
      spinning: false,
      showPreviewImg: false,
      previewUrl: ''
    }
  },
  watch: {
    perfectNum: {
      immediate: true,
      handler: function (perfectNum) {
        if (perfectNum > 0) {
          this.$set(this.tabs[1], 'name', '待完善(' + perfectNum + ')')
        } else {
          this.$set(this.tabs[1], 'name', '待完善')
        }
      }
    },
    type: {
      immediate: true,
      handler: function (type) {
        if (type == 1) {
          this.columns = columns2
        } else {
          this.columns = columns
        }
      }
    },
  },
  computed: {
    formatLabel() {
      return function (ids) {
        if (ids == '') {
          return ''
        }
        const idArr = ids.split(',')
        const results = []
        this.styleOptions.forEach(item => {
          if (idArr.includes(item.id.toString())) {
            results.push(item.labelName)
          }
        })
        return results.join('/')
      }
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  mounted() {
    this.lookTypeList()
  },
  methods: {
    batch,
    prevHandle(url) {
      if (url) {
        this.showPreviewImg = true,
          this.previewUrl = url
      }
    },
    async batchUpdate(status) {
      const { selectedRowKeys: id } = this

      const res = await batchUpdateMore({ id, status })
      this.spinning = false
      if (res.code == 200) {
        this.reCalculatePage(1)
        this.loadData()
        this.getNum()
        this.$message.success(`批量${status == 3 ? '禁用' : '启用'}成功`)
        this.clearKeys()
      }
    },
    async batchDelete() {
      const { selectedRowKeys: id } = this
      const res = await batchDeleteMore({ id })
      this.spinning = false
      if (res.code == 200) {
        this.clearKeys()
        this.$message.success('批量删除成功')
        this.visible = false
        this.reCalculatePage(1)
        this.loadData()
        this.getNum()
      }

    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async getNum() {
      const res = await moreHandleNum()
      this.perfectNum = res.data
    },
    updateStatus(id, status) {
      this.$confirm({
        content: status == 3 ? '禁用后将不会出现在主款详情页' : '启用后将有可能出现在主款详情页',
        cancelText: '暂不',
        onOk: res => {
          return new Promise(async (resolve, reject) => {
            const res = await updateMoreCollocationStatus({ id, status })
            if (res.code == 200) {
              this.reCalculatePage(1)
              this.loadData()
              this.$message.success(`${status == 3 ? '禁用' : '启用'}成功`)
              resolve(true)
            } else {
              this.$message.error(res.msg)
              reject(false)
            }
          })
        },
        onCancel() { }
      })
    },
    handleEdit(record, differencePage = 0) {
      const query = {
        id: record.id,
        differencePage,
        productNoMoreList: record.collocationProductList.map(item => item.productNoMore),
        status: this.type == 3 ? 3 : 2
      }
      console.log(query)
      this.$router.push({
        path: `/micromall/marketing/collocation/more/edit`,
        query: {
          obj: JSON.stringify(query)
        }
      })
    },
    loadData(current) {
      if(this.$route.path != '/micromall/marketing/collocation/more') return
      // if (!this.url.list) {
      //   this.$message.error('请设置url.list属性!')
      //   return
      // }
      //加载数据 若传入参数1则加载第一页的内容
      this.loading = true
      if (current === 1) {
        this.pagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      // 增加状态
      params.status = this.type
      listMore(params).then(res => {
        if (res.code == 200) {
          this.dataSource = res.data.records || res.data
          if (res.data.total) {
            this.pagination.total = res.data.total
          } else {
            this.pagination.total = 0
          }
        } else {
          this.$message.warning(res.msg)
        }
        this.loading = false
      })
      this.getNum()
    },
    async styleList() {
      const re = await lookLabel({ code: 'B08-A01' })
      console.log(re)
      this.styleOptions = re.data
    },
    async lookTypeList() {
      const re = await lookLabel({ code: 'B10-A02' })
      console.log(re)
      this.lookTypes = re.data
    },
    tabChange(type) {
      this.type = type
      this.selectedRowKeys = []
      // 加载第一页
      this.loadData(1)
    },
    add() { },
    async deleteCollcation(id) {
      this.$confirm({
        content: '确定删除该套搭配吗？',
        cancelText: '暂不',
        onOk: res => {
          return new Promise((resolve, reject) => {
            removeMoreCollocation(id)
              .then(res => {
                if (res.code == 200) {
                  this.visible = false
                  this.reCalculatePage(1)
                  this.loadData()
                  this.$message.success('删除成功')
                  resolve()
                } else {
                  this.$message.success(res.msg)
                  reject()
                }
              })
              .catch(err => {
                resolve()
                console.log(err)
              })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() { }
      })
    }
  }
}
</script>
<style scoped>
.goods-img {
  width: 50px;
  height: 50px;
}

.goods-img:not(:last-child) {
  margin-right: 10px;
}</style>
